package com.shuoyue.ycgk.ui.pay;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.ahammertest.ycgk.pay.PaySucEvent;
import com.ahammertest.ycgk.pay.alipay.Alipay;
import com.ahammertest.ycgk.pay.alipay.PayResult;
import com.ahammertest.ycgk.wxapi.WxPay;
import com.ahammertest.ycgk.wxapi.WxPayBean;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.entity.Coupon;
import com.shuoyue.ycgk.entity.VipPrice;
import com.shuoyue.ycgk.ui.mine.coupon.CouponSelectActivity;
import com.shuoyue.ycgk.utils.XToast;
import com.shuoyue.ycgk.views.dialog.common.HintDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 预览Vip订单
 */
public class PreVipActivity extends BaseMvpActivity<PreOrderContract.Presenter>
        implements PreOrderContract.View {
    protected OrderPriceInfo orderPriceInfo;
    VipPrice data;
    @BindView(R.id.page_title)
    TextView pageTitle;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.coupon)
    TextView coupon;
    @BindView(R.id.layCoupon)
    LinearLayout layCoupon;
    @BindView(R.id.wx_pay)
    CheckBox wxPay;
    @BindView(R.id.lay_wx)
    LinearLayout layWx;
    @BindView(R.id.alpay)
    CheckBox alpay;
    @BindView(R.id.lay_ali)
    LinearLayout layAli;
    @BindView(R.id.lay_pay)
    LinearLayout layPay;
    @BindView(R.id.price_sum_total)
    TextView priceSumTotal;
    @BindView(R.id.buy)
    TextView buy;
    @BindView(R.id.remark)
    protected EditText remark;

    private OrderNo orderNo;
    Coupon selectCoupon;

    int subjectTypeId;
    String subjectName;

    public static void start(Context source, VipPrice price, int subjectTypeId, String subjectName) {
        source.startActivity(new Intent(source, PreVipActivity.class)
                .putExtra("subjectTypeId", subjectTypeId)
                .putExtra("subjectName", subjectName)
                .putExtra("data", price));
    }

    /**
     * 初始化layouy
     */
    @Override
    protected int getLayoutId() {
        return R.layout.activity_pre_vip_order;
    }

    @Override
    protected void initView() {
        pageTitle.setText("确认订单");
    }

    @Override
    public void initData() {
        super.initData();
        data = (VipPrice) getIntent().getSerializableExtra("data");
        subjectTypeId = getIntent().getIntExtra("subjectTypeId", 39);
        subjectName = getIntent().getStringExtra("subjectName");


        EventBus.getDefault().register(this);
        mPresenter = new PreOrderContract.Presenter();
        mPresenter.attachView(this);
        getPriceInfo();

    }

    private void getPriceInfo() {
        if (data != null)
            mPresenter.getPriceInfo(data.getId(),
                    1,
                    data.getId(),
                    5,
                    null,
                    selectCoupon == null ? null : selectCoupon.getId());
    }

    @OnClick({R.id.back,
            R.id.layCoupon, R.id.buy,
            R.id.lay_wx, R.id.wx_pay, R.id.lay_ali, R.id.alpay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.layCoupon:
                startActivityForResult(new Intent(mContext, CouponSelectActivity.class)
                                .putExtra("useType", 5)
                                .putExtra("subjectType", subjectTypeId)
                        , 1044);
//                startActivityForResult(new Intent(mContext, CouponSelectActivity.class), 1044);
                break;
            case R.id.buy:
                buy();
                break;
            case R.id.lay_wx:
            case R.id.wx_pay:
                switchPayType(1);
                break;
            case R.id.lay_ali:
            case R.id.alpay:
                switchPayType(2);
        }
    }


    //1:微信;2阿里
    void switchPayType(int type) {
        if (type == 1) {
            wxPay.setChecked(true);
            alpay.setChecked(false);
        } else {
            wxPay.setChecked(false);
            alpay.setChecked(true);
        }

    }

    void buy() {
        int payType = 0;
        if (wxPay.isChecked()) {
            payType = 1;
        } else if (alpay.isChecked()) {
            payType = 2;
        }
        if (payType == 0) {
            XToast.toast(mContext, "请选择支付方式");
        } else {
            buy.setEnabled(false);
            mPresenter.submitOrder(
                    data.getSubjectTypeId(),
                    orderPriceInfo.getProductNum(),
                    data.getId(),
                    5,
                    payType,
                    null,
                    selectCoupon == null ? null : selectCoupon.getId(), remark.getText().toString());
        }
    }


    @Override
    public void setPriceInfo(OrderPriceInfo priceInfo) {
        this.orderPriceInfo = priceInfo;
        title.setText(priceInfo.getName() + "(" + subjectName + ")");
        price.setText("￥" + priceInfo.getUnitPrice());//((item.getPrice() % 1f == 0) ? ((int) item.getPrice()) : item.getPrice())
        priceSumTotal.setText("￥" + priceInfo.getPayPrice());//((item.getPrice() % 1f == 0) ? ((int) item.getPrice()) : item.getPrice())
//        coupon.setText("￥" + priceInfo.getCouponPrice());

        if (priceInfo.getHasCoupon() == 0) {
            coupon.setText("暂无可用优惠券");
        } else {
            if (priceInfo.getCouponPrice() == 0) {
                coupon.setText("请选择");
            } else {
                coupon.setText("已优惠:￥" + priceInfo.getCouponPrice());//((item.getPrice() % 1f == 0) ? ((int) item.getPrice()) : item.getPrice())
            }

        }

    }

    @Override
    public void getPriceInfoFail() {
        selectCoupon = null;
    }


    @Override
    public void createOrderSuc(OrderNo orderCode, int type) {
        this.orderNo = orderCode;
//        if (type == 1) {
//            mPresenter.getWxPayInfo(orderCode.getOrderNo());
//        } else {
//            mPresenter.getAliPayInfo(orderCode.getOrderNo());
//
//        }

        this.orderNo = orderCode;
        if (orderCode == null) {
            //直接成功
            HintDialog hintDialog = new HintDialog(mContext, "提示", "领取成功");
            hintDialog.setOkListener(v -> {
                hintDialog.dismiss();
                finish();
            });
            hintDialog.setCancelable(false);
            hintDialog.setCanceledOnTouchOutside(false);
            hintDialog.show();
        } else {
//        XToast.toast(mContext, "订单编号:" + orderCode.getOrderNo());
            if (type == 1) {
                mPresenter.getWxPayInfo(orderCode.getOrderNo());
            } else {
                mPresenter.getAliPayInfo(orderCode.getOrderNo());
            }
        }
    }

    @Override
    public void getWxPayInfoSuc(WxPayBean o) {
        WxPay.pay(this, o);
    }

    @Override
    public void getAliPaySuc(String info) {
        Alipay.pay(this, info, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    PayResult payResult = (PayResult) msg.obj;
                    Log.e("alipay", payResult.toString());
                    try {
                        JSONObject jsonObject = new JSONObject(payResult.getResult());
                        JSONObject resultcodes = jsonObject.optJSONObject("alipay_trade_app_pay_response");
                        String code = resultcodes.optString("code");
                        Log.e("code", code);
                        if (code.equals("10000")) {
                            PayResult(new PaySucEvent(1));
                        } else {
                            PayResult(new PaySucEvent(2));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        PayResult(new PaySucEvent(2));
                    }
                }
            }
        });
    }

    @Override
    public void enableButtonPay() {
        buy.setEnabled(true);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void PayResult(PaySucEvent event) {
        if (event.getPayStatus() == 1) {
            XToast.toast(mContext, "支付成功");
            finish();

        } else {
//            XToast.toast(mContext, "支付失败,请联系客服");
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1044 && resultCode == RESULT_OK) {
            selectCoupon = (Coupon) data.getSerializableExtra("data");
            getPriceInfo();
        }
    }


}
